/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import { uniqueId } from 'lodash';
import { Toaster } from '@blueprintjs/core';

// Utils
import { Settings } from './Settings';
import { log } from './dev-logs';

class Saiku {
  /**
   * Return a simple class to display toasts
   *
   * @example:
   *
   *    Saiku.toasts().show({ message: data, intent: Intent.DANGER });
   *
   *    or
   *
   *    Saiku.toasts(Position.TOP_RIGHT).show({ message: data, intent: Intent.DANGER });
   */
  static toasts(position = null) {
    return Toaster.create(position ? { position } : {});
  }

  /**
   * Generate UID for an item
   *
   * @example:
   *
   *    <li key={`${Saiku.uid(key)}`}>Unit Sales</li>
   */
  static uid(item) {
    if (typeof item === 'number' || typeof item === 'string') {
      return `${uniqueId(`${item}_`)}`;
    }

    log('The value for the uid must be a "string" or "number".', 'warn');
  }

  /**
   * Get a query property
   *
   * @example:
   *
   *    Saiku.getProperty('saiku.olap.result.formatter', query)
   */
  static getProperty(propertyName, query) {
    return query && query.properties ? query.properties[propertyName] : null;
  }

  /**
   * Trim first or last char or both
   *
   * @example:
   *
   *    Saiku.trimFirstLastChar('Saiku Analytics', 'first'); // -> aiku Analytics
   *    Saiku.trimFirstLastChar('Saiku Analytics', 'last');  // -> Saiku Analytic
   *    Saiku.trimFirstLastChar('Saiku Analytics');          // -> aiku Analytic
   */
  static trimFirstLastChar(value, trimPosChar) {
    const str = value.toString();

    if (trimPosChar === 'first' || trimPosChar === 'f') {
      return str.substring(1, str.length);
    } else if (trimPosChar === 'last' || trimPosChar === 'l') {
      return str.substring(0, str.length - 1);
    } else {
      // Trim first and last char
      return str.substring(1, str.length - 1);
    }
  }

  // Check if it's Saiku demo running
  static isSaikuDemo = () => {
    return (
      window.location.hostname &&
      window.location.hostname === Settings.SAIKU_DEMO_URL
    );
  };

  // Reference: https://github.com/axios/axios#handling-errors
  static axiosHandleErrors(name, error) {
    if (name) {
      log(`Logging for: ${name}`);
    }

    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.error(error.response.data);
      console.error(error.response.status);
      console.error(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.error(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Error', error.message);
    }

    console.error(error.config);
  }
}

export default Saiku;
